﻿using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using Commons.Daos;
using Commons.Injector;
using Commons.Preferences;
using Commons.Utils;

namespace Commons.Loading
{
	public class CheckDataBaseTask : BasicLoadingTask
	{
		public override IEnumerator Update()
		{
			return CollectionsHelper.SafeEnumerator(SafeUpdate());
		}

		private IEnumerator SafeUpdate()
		{
			bool databaseExists = PersistenceManager.Exists();

			if (databaseExists)
			{
				using (SqlConnection connection = new SqlConnection("URI=file:" + PersistenceManager.GetDatabaseFilename()))
				{
					connection.Open();

					bool isOk = false;

					using (SqlCommand command = new SqlCommand("PRAGMA integrity_check", connection))
					using (DbDataReader reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							string diagnostic = reader.GetString(0);

							if (diagnostic == "ok")
							{
								isOk = true;
							}
							else
							{
								Debug.LogErrorFormat("Database integrity_check: {0}", diagnostic);
							}
						}
					}

					yield return null;

					if (!isOk)
					{
						using (SqlCommand command = new SqlCommand("REINDEX", connection))
						{
							command.ExecuteNonQuery();
						}

						Debug.Log("Database reindex");

						yield return null;

						using (SqlCommand command = new SqlCommand("VACUUM", connection))
						{
							command.ExecuteNonQuery();
						}

						Debug.Log("Database vacuum");

						yield return null;
					}

					connection.Close();
				}
			}
		}
	}
}